package com.yuyou.fn.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.service.IEmailService;
import com.yuyou.fn.common.service.ISiteConfigService;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Sms 表数据服务层接口实现类
 */
@Service
public class EmailServiceImpl   implements IEmailService {


    @Resource
    private ISiteConfigService siteConfigService;

    private static String route="/api/message/sendEmail";



    @Override
    public void sendEmail(String toAddress, String subject, String content,List<String> urls, List<String> names) {

        OkHttpClient client = new OkHttpClient.Builder().retryOnConnectionFailure(true).connectTimeout(30, TimeUnit.SECONDS ).readTimeout(10,TimeUnit.SECONDS).build();
        String url  =  siteConfigService.findConfigValue("yyfn_message")+route;
        String token=siteConfigService.findConfigValue("yyfn_message_token");
        Map<String,String> params = new HashMap<>();
        params.put("toAddress" ,toAddress);
        params.put("subject" ,subject );
        params.put("content" ,content );
        String urlString=StringUtils.join(urls,",");
        if (StringUtils.isNotEmpty(urlString)){
            params.put("urls" ,urlString);
        }
        String nameString=StringUtils.join(names,",");
        if (StringUtils.isNotEmpty(nameString)){
            params.put("names" ,nameString);
        }

        params.put("token", DigestUtils.md5Hex(toAddress+token));
        FormBody.Builder formBody = new FormBody.Builder();
        for(Map.Entry<String,String> entry : params.entrySet() ){
            formBody.add(entry.getKey(),entry.getValue());
        }
        Request request = new Request.Builder().url(url).post(formBody.build()).build() ;
        try {
            Response response = client.newCall(request).execute();
            if (response.code()!=200){
                throw new BusException("网络错误");
            }
            String result=response.body().string() ;
            JSONObject jsonObject=JSONObject.parseObject(result);
            int resultCode=jsonObject.getIntValue("resultCode");
            String message=jsonObject.getString("message");
            if (resultCode!=0){
                throw new BusException(message);
            }

        }catch (Exception e){
            throw new BusException(e.getMessage());
        }
    }


}